{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68e3feb7",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
    "\n",
    "Instructions for setting up Colab are as follows:\n",
    "1. Open a new Python 3 notebook.\n",
    "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
    "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
    "4. Run this cell to set up dependencies.\n",
    "5. Restart the runtime (Runtime -> Restart Runtime) for any upgraded packages to take effect\n",
    "\"\"\"\n",
    "## Install dependencies\n",
    "!pip install wget\n",
    "!apt-get install libboost-all-dev\n",
    "!apt-get install gawk\n",
    "\n",
    "## Install NeMo\n",
    "BRANCH = 'main'\n",
    "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n",
    "\n",
    "!pip uninstall -y sacrebleu\n",
    "!pip install sacrebleu[ja]\n",
    "!pip install xxhash\n",
    "\n",
    "## Install kenlm with 7-gram support\n",
    "!mkdir -p data\n",
    "!rm -rf data/kenlm\n",
    "!git clone https://github.com/kpu/kenlm data/kenlm\n",
    "!cd data/kenlm \\\n",
    "    && pip install . --install-option=\"--max_order 7\" \\\n",
    "    && mkdir -p build \\\n",
    "    && cd build \\\n",
    "    && cmake .. -DKENLM_MAX_ORDER=7 -DCMAKE_INSTALL_PREFIX:PATH=../../kenlm_install \\\n",
    "    && make -j all install && cd ../../kenlm_install \\\n",
    "    && export PATH=$PATH:$PWD\n",
    "\n",
    "# Install bicleaner\n",
    "\n",
    "!pip install bicleaner"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0075e98c",
   "metadata": {},
   "source": [
    "# Data Preprocessing & Cleaning for NMT\n",
    "\n",
    "This notebook contains a tutorial of data processing and cleaning for NMT (Neural Machine Translation) to train translation models with the [NeMo framework](https://github.com/NVIDIA/NeMo).\n",
    "\n",
    "A pre-requisite to train supervised neural machine translation systems is the availability of *parallel corpora* of reasonable quality.\n",
    "\n",
    "A parallel corpus is a collection of sentences or documents that are translations of each other in 2 or more languages.\n",
    "\n",
    "For example,\n",
    "\n",
    "| English                                                                            | Russian |\n",
    "| :-: | :-: |\n",
    "| To date, a total of 43 participants from 15 countries have completed the training. | К настоящему времени подготовку прошли в общей сложности 43 участника из 15 стран . |\n",
    "| M-Sport Bentley writes a new piece of Bentley history at Silverstone | M-Sport Bentley открывает новую страницу в истории Bentley в Сильверстоуне |\n",
    "| Information in the application was not true. | Информация в заявлении не была достоверна. |\n",
    "\n",
    "This notebook will cover the following data pre-processing and data cleaning techniques for such corpora.\n",
    "\n",
    "## The importance of data cleaning\n",
    "\n",
    "The presence of noise in the training dataset can adversely affect model quality (https://arxiv.org/abs/1805.12282). Webcrawled and automatically aligned data sources in particular, such as [Paracrawl](https://paracrawl.eu/), [WikiMatrix](https://arxiv.org/abs/1907.05791), [CC-Aligned](https://arxiv.org/abs/1911.06154) and [CC-Matrix](https://arxiv.org/abs/1911.04944) can be extremely noisy.\n",
    "\n",
    "## Cleaning\n",
    "1. Downloading and filtering publicly available datasets based on confidence thresholds (if available). For example, [WikiMatrix](https://arxiv.org/abs/1907.05791) filtering based on [LASER](https://arxiv.org/abs/1812.10464) confidence scores.\n",
    "2. Language ID filtering using a pre-trained [fastText classifier](https://fasttext.cc/docs/en/language-identification.html). This step will remove all sentences from the parallel corpus that our classifier predicts as not being in the appropriate language (ex: sentences in the English column that aren't in English or sentences in Russian column that aren't in Russian).\n",
    "3. Length and Length-ratio filtering. This steps removes all sentences that are 1) too long 2) too short or 3) have a ratio between their lengths greater than a certain factor (this typically removes partial translations).\n",
    "4. [Bicleaner](https://github.com/bitextor/bicleaner) classifier-based cleaning. Bicleaner identifies noisy parallel sentences using a classifier that leverages multiple features such as n-gram language model likelihood scores, word alignment scores and other heuristics.\n",
    "\n",
    "## Pre-processing\n",
    "5. [Moses Punctuation Normalization](https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/normalize-punctuation.perl). This step standardizes punctuation. For example the less common way to write apostrophes Tiffany`s will be standardized to Tiffany's.\n",
    "6. Unicode standardization. There exist some unicode characters that aren't punctuation that need to be standardized for example, this step normalizes the number ４ to 4.\n",
    "7. [Moses Tokenization](https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/tokenizer.perl) or text segmentation for Chinese/Japanese with [Jieba](https://github.com/fxsjy/jieba) and [mecab](https://github.com/taku910/mecab). For languages like Chinese and Japanese that do not have explicit word segmentation markers (like spaces), we use these tools to introduce spaces into the text that will let us split the string into words. For other languages, we use Moses to separate punctuation markers from words so that they become separate tokens.\n",
    "8. Deduplication - This step removes duplicate translation pairs from the corpus.\n",
    "9. Shuffling - This step shuffles the order of occurrence of translation pairs.\n",
    "\n",
    "## Tarred Datasets for Large Corpora\n",
    "10. Large datasets with over 50M sentence pairs when batched and pickled can be up to 60GB in size. Loading them entirely into CPU memory when using say 8 or 16 workers with DistributedDataParallel training uses 480-960GB of RAM which is often impractical and inefficient. Instead, we use [Webdataset](https://github.com/webdataset/webdataset) to allow training while keeping datasets on disk and let webddataset handle pre-loading and fetching of data into CPU RAM.\n",
    "\n",
    "\n",
    "## Disclaimer\n",
    "\n",
    "The data cleaning techniques used in this notebook are only meant to be loose guidelines and are not guaranteed to produced clean parallel corpora at the end of it. Not all of these steps are a necessity for every dataset, "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb0eb698",
   "metadata": {},
   "source": [
    "![NMT Data Pipeline](images/nmt_data_pipeline.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a9fd8d3",
   "metadata": {},
   "source": [
    "# Downloading Publicly Available Data\n",
    "\n",
    "## WikiMatrix (https://arxiv.org/abs/1907.05791)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78984523",
   "metadata": {},
   "outputs": [],
   "source": [
    "!mkdir -p data\n",
    "print('Downloading data ...')\n",
    "!wget https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-ru.tsv.gz -O data/WikiMatrix.en-ru.tsv.gz\n",
    "print('---------------------')\n",
    "print('Unzipping file ...')\n",
    "!gunzip -k -f data/WikiMatrix.en-ru.tsv.gz\n",
    "print('---------------------')\n",
    "print('Peek into the file')\n",
    "!head -10 data/WikiMatrix.en-ru.tsv\n",
    "print('---------------------')\n",
    "print('File length ...')\n",
    "!wc -l data/WikiMatrix.en-ru.tsv\n",
    "print('---------------------')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9a62f9e",
   "metadata": {},
   "source": [
    "## Filter Based on LASER Confidence\n",
    "\n",
    "LASER (https://arxiv.org/abs/1812.10464) is a multi-lingual neural sentence embedding model that is often used for cross-lingual sentence/document retrieval. Similarities in the embedding space are often used as proxies for cross-lingual similarities."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21608388",
   "metadata": {},
   "outputs": [],
   "source": [
    "from tqdm import tqdm\n",
    "import numpy as np\n",
    "\n",
    "def num_lines_in_file(fname):\n",
    "    \"\"\"\n",
    "    Returns the number of lines in a file.\n",
    "    \"\"\"\n",
    "    with open(fname, 'r') as f:\n",
    "        for i, _ in enumerate(f):\n",
    "            pass\n",
    "    return i + 1\n",
    "\n",
    "def filter_tsv_with_conf(\n",
    "    input_file, output_file_lang_1, output_file_lang_2,\n",
    "    confidence_threshold=None, confidence_column=None\n",
    "):\n",
    "    \"\"\"\n",
    "    Filters a tsv file that has confidence scores associated with each parallel example.\n",
    "\n",
    "    For example:\n",
    "\n",
    "    1.23 \\t This is a sentence in lang1 \\t This is a sentence in lang2\n",
    "    \"\"\"\n",
    "    print()\n",
    "    print('====================================')\n",
    "    print('======= TSV Conf Filtering =========')\n",
    "    print('====================================')\n",
    "    print()\n",
    "    num_lines = num_lines_in_file(input_file)\n",
    "    scores = []\n",
    "    num_output_lines = 0\n",
    "    lang_1_col = 0\n",
    "    lang_2_col = 1\n",
    "    with open(input_file, 'r') as f, \\\n",
    "        open(output_file_lang_1, 'w') as f_out_1, \\\n",
    "        open(output_file_lang_2, 'w') as f_out_2:\n",
    "        for line in tqdm(f, total=num_lines, desc=f\"Filtering file by confidence {confidence_threshold}\"):\n",
    "            if line.strip() == '':\n",
    "                continue\n",
    "            line = line.strip().split('\\t')\n",
    "            if len(line) < 2:\n",
    "                continue\n",
    "            if confidence_threshold is not None and float(line[confidence_column]) < confidence_threshold:\n",
    "                continue\n",
    "            else:\n",
    "                if confidence_threshold is not None:\n",
    "                    scores.append(float(line[confidence_column]))\n",
    "                    if confidence_column == 0:\n",
    "                        lang_1_col, lang_2_col = 1, 2\n",
    "                    elif confidence_column == 2:\n",
    "                        lang_1_col, lang_2_col = 0, 1\n",
    "                    elif confidence_column == 1:\n",
    "                        lang_1_col, lang_2_col = 0, 2\n",
    "                    else:\n",
    "                        raise ValueError(f\"Invalid Column for confidence {confidence_column}\")\n",
    "                f_out_1.write(line[lang_1_col] + '\\n')\n",
    "                f_out_2.write(line[lang_2_col] + '\\n')\n",
    "                num_output_lines += 1\n",
    "\n",
    "    if confidence_threshold is not None:\n",
    "        print(f'Confidence score average  : {np.mean(scores)}')\n",
    "        print(f'Confidence score variance : {np.var(scores)}')\n",
    "        print(f'Kept {num_output_lines} out of {num_lines} after conversion ({(num_output_lines / num_lines) * 100}%)')\n",
    "        print('====================================')\n",
    "\n",
    "filter_tsv_with_conf(\n",
    "    'data/WikiMatrix.en-ru.tsv',\n",
    "    'data/WikiMatrix.en-ru.en', \n",
    "    'data/WikiMatrix.en-ru.ru',\n",
    "    confidence_threshold=1.04, confidence_column=0\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18a171d1",
   "metadata": {},
   "source": [
    "## Language ID filtering with fastText\n",
    "\n",
    "Noisy parallel corpora often contain sentences that are not in the intended language. A classifier that determines the language in which a sentence is written can be used to filter out sentences that aren't in the appropriate language."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d58b7148",
   "metadata": {},
   "outputs": [],
   "source": [
    "!wget https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.bin -O data/lid.176.bin\n",
    "print()\n",
    "print('====================================')\n",
    "print('====== Language ID Filtering =======')\n",
    "print('====================================')\n",
    "print()\n",
    "\n",
    "\n",
    "!wget https://raw.github.com/NVIDIA/NeMo/main/scripts/neural_machine_translation/filter_langs_nmt.py \\\n",
    "    -O filter_langs_nmt.py\n",
    "\n",
    "!python filter_langs_nmt.py \\\n",
    "    --input-src data/WikiMatrix.en-ru.en  \\\n",
    "    --input-tgt data/WikiMatrix.en-ru.ru \\\n",
    "    --output-src data/WikiMatrix.en-ru.langidfilter.en  \\\n",
    "    --output-tgt data/WikiMatrix.en-ru.langidfilter.ru  \\\n",
    "    --source-lang en \\\n",
    "    --target-lang ru \\\n",
    "    --removed-src data/WikiMatrix.en-ru.langidfilter.removed.en  \\\n",
    "    --removed-tgt data/WikiMatrix.en-ru.langidfilter.removed.ru  \\\n",
    "    --fasttext-model data/lid.176.bin\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Number of removed sentences:')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "!wc -l data/WikiMatrix.en-ru.langidfilter.removed.ru\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Examples of removed sentences')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "!paste -d \"\\t\" \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.removed.en \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.removed.ru \\\n",
    "    | head -10\n",
    "print('-----------------------------------------')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffb42e92",
   "metadata": {},
   "source": [
    "## Length and Ratio Filtering\n",
    "\n",
    "This step filters out sentences based on their lengths and the ratio between source and target lengths. If (a) src_len / tgt_len or tgt_len / src_len exceed 1.3 or (b) source or target sequence lengths are less than 1 or greater than 250, the sentence pair will be removed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52ff172a",
   "metadata": {},
   "outputs": [],
   "source": [
    "!git clone https://github.com/moses-smt/mosesdecoder data/mosesdecoder\n",
    "!cd data/mosesdecoder && git checkout RELEASE-4.0 && cd ../..\n",
    "!perl data/mosesdecoder/scripts/training/clean-corpus-n.perl -ratio 1.3 \\\n",
    "    data/WikiMatrix.en-ru.langidfilter \\\n",
    "    en ru \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio \\\n",
    "    1 250"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "01f2b589",
   "metadata": {},
   "source": [
    "## Bicleaner Filtering\n",
    "\n",
    "Bicleaner (https://aclanthology.org/W18-6488/ and https://aclanthology.org/2020.eamt-1.31/) is a tool to identify noisy parallel sentences in translation corpora. It applies 3 different filtering steps:\n",
    "\n",
    "1. Pre-filtering based on 37 rules.\n",
    "2. Language model fluency scores based on n-gram language models trained with kenlm.\n",
    "3. Random forest classifier that uses all examples filtered out in steps 1 & 2 as \"negative\" examples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9be8d4ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Downloading En-Ru Bicleaner models.')\n",
    "!git clone https://github.com/bitextor/bicleaner data/bicleaner\n",
    "!cd data/bicleaner && git checkout bicleaner-0.15 && cd ../..\n",
    "!data/bicleaner/utils/download-pack.sh en ru\n",
    "\n",
    "print('Generating Bicleaner scores ...')\n",
    "!gawk '{{print \"-\\t-\"}}' \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.en | \\\n",
    "    paste -d \"\\t\" - data/WikiMatrix.en-ru.langidfilter.lengthratio.en \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.ru | \\\n",
    "    bicleaner-classify - - en-ru/en-ru.yaml \\\n",
    "    > data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43059b8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Score file ...')\n",
    "!head -10 data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Filtering based on Bicleaner scores > 0.6 ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "print('Filtering out English ...')\n",
    "!gawk -F \"\\t\" '{if ($5>0.6) {print $3}}' \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en\n",
    "\n",
    "print('Filtering out Russian ...')\n",
    "!gawk -F \"\\t\" '{if ($5>0.6) {print $4}}' \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru\n",
    "\n",
    "!paste -d \"\\t\" \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru \\\n",
    "    | head -10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0726510c",
   "metadata": {},
   "source": [
    "## Normalize Punctuation\n",
    "\n",
    "Punctuation can vary across languages and even between ascii and unicode variants of the same punctuation marker. For example, across languages. For example, in German, quotes are often written as „ and “ while in English we typically just use \". This step normalizes such punctuation differences to use the same character everywhere.\n",
    "\n",
    "We use [moses](https://github.com/moses-smt/mosesdecoder) or [sacremoses](https://github.com/alvations/sacremoses) to normalize punctuation. The moses implementation is in perl while sacremoses is in python with a CLI interface. The perl implementation is buffered and works better for large corpora that may not fit into CPU memory all at once while sacremoses is unbuffered and multi-processed."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e73670d6",
   "metadata": {},
   "source": [
    "### Sacremoses"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "597e041a",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Normalizing English ...')\n",
    "!sacremoses -j 4 normalize \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.en\n",
    "\n",
    "print('Normalizing Russian ...')\n",
    "!sacremoses -j 4 normalize \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.ru\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "240b0a1f",
   "metadata": {},
   "source": [
    "## Moses\n",
    "\n",
    "Punctuation can vary across languages and even between ascii and unicode variants of the same punctuation marker. For example, across languages. For example, in German, quotes are often written as „ and “ while in English we typically just use \". This step normalizes such punctuation differences to use the same character everywhere.\n",
    "\n",
    "We use [moses](https://github.com/moses-smt/mosesdecoder) or [sacremoses](https://github.com/alvations/sacremoses) to normalize punctuation. The moses implementation is in perl while sacremoses is in python with a CLI interface. The perl implementation is buffered and works better for large corpora that may not fit into CPU memory all at once while sacremoses is unbuffered and multi-processed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f5adaa4",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Normalizing English ...')\n",
    "!perl data/mosesdecoder/scripts/tokenizer/normalize-punctuation.perl -l en \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.en\n",
    "\n",
    "print('Normalizing Russian ...')\n",
    "!perl data/mosesdecoder/scripts/tokenizer/normalize-punctuation.perl -l ru \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.ru\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8bfad64",
   "metadata": {},
   "source": [
    "## Tokenize\n",
    "\n",
    "Tokenization splits a string into a sequence of tokens. A naive way of doing this would be to simply split the string on spaces (for languages where this is possible). This however, will result in punctuation being \"attached\" to the neighboring word when tokenizing. For example, \n",
    "\n",
    "\"This is a sentence.\" will be tokenized as [\"This, is, a, sentence.\"].\n",
    "\n",
    "However, we'd typically like punctuation to be separate tokens for example,\n",
    "\n",
    "\"This is a sentence.\" will be tokenized my moses or sacremoses as [\", This, is, a, sentence, ., \"]."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06c60b90",
   "metadata": {},
   "source": [
    "### Sacremoses"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7bb4c631",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Tokenizing English ...')\n",
    "!sacremoses -j 4 -l en tokenize -x \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.en > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.tok.en\n",
    "\n",
    "print('Tokenizing Russian ...')\n",
    "!sacremoses -j 4 -l ru tokenize -x \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.ru > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.tok.ru\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "444bebd7",
   "metadata": {},
   "source": [
    "### Moses"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21333e27",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Tokenizing English ...')\n",
    "!perl data/mosesdecoder/scripts/tokenizer/tokenizer.perl -l en -no-escape -threads 4 \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.en > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.en\n",
    "\n",
    "print('Tokenizing Russian ...')\n",
    "!perl data/mosesdecoder/scripts/tokenizer/tokenizer.perl -l ru -no-escape -threads 4 \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.ru > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.ru\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b28df2bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Tokenized Russian Sentences ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "!head -10 data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.ru\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Tokenized English Sentences ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "!head -10 data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.en"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dee5409d",
   "metadata": {},
   "source": [
    "## Segmenting Chinese and Japanese\n",
    "\n",
    "### Jieba segmentation for Chinese"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41b4cc91",
   "metadata": {},
   "outputs": [],
   "source": [
    "import jieba\n",
    "\n",
    "!wget https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-zh.tsv.gz -O data/WikiMatrix.en-zh.tsv.gz\n",
    "!gunzip -k -f data/WikiMatrix.en-zh.tsv.gz\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Chinese text before segmentation ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "!awk -F \"\\t\" '{print $3}' data/WikiMatrix.en-zh.tsv | head -10\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Segmenting Chinese text ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "zh_lines = []\n",
    "with open('data/WikiMatrix.en-zh.tsv', 'r') as f:\n",
    "    for idx, line in enumerate(f):\n",
    "        line = line.strip().split('\\t')[2]\n",
    "        zh_lines.append(' '.join(jieba.cut(line)))\n",
    "        if idx == 100:\n",
    "            break\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Chinese text after segmentation ...')\n",
    "print('\\n'.join(zh_lines[:10]))\n",
    "print('-----------------------------------------')\n",
    "print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "489bd915",
   "metadata": {},
   "outputs": [],
   "source": [
    "import MeCab\n",
    "import ipadic\n",
    "\n",
    "!wget https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-ja.tsv.gz -O data/WikiMatrix.en-ja.tsv.gz\n",
    "!gunzip -k -f data/WikiMatrix.en-ja.tsv.gz\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Japanese text before segmentation ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "!awk -F \"\\t\" '{print $3}' data/WikiMatrix.en-ja.tsv | head -10\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Segmenting Japanese text ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "mecab_tokenizer = MeCab.Tagger(ipadic.MECAB_ARGS + \" -Owakati\")\n",
    "\n",
    "ja_lines = []\n",
    "with open('data/WikiMatrix.en-ja.tsv', 'r') as f:\n",
    "    for idx, line in enumerate(f):\n",
    "        line = line.strip().split('\\t')[2]\n",
    "        ja_lines.append(mecab_tokenizer.parse(line))\n",
    "        if idx == 100:\n",
    "            break\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Japanese text after segmentation ...')\n",
    "print('\\n'.join(ja_lines[:10]))\n",
    "print('-----------------------------------------')\n",
    "print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a079efe",
   "metadata": {},
   "source": [
    "## Deduplicate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55d98bf3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import xxhash\n",
    "\n",
    "def dedup_file(input_file_lang_1, input_file_lang_2, output_file_lang_1, output_file_lang_2):\n",
    "    print()\n",
    "    print('====================================')\n",
    "    print('========== De-duplicate ============')\n",
    "    print('====================================')\n",
    "    print()\n",
    "    num_lines = num_lines_in_file(input_file_lang_1)\n",
    "    hashes = set()\n",
    "    num_output_lines = 0\n",
    "    with open(input_file_lang_1, 'r') as f_lang1, \\\n",
    "        open(input_file_lang_2, 'r')  as f_lang2, \\\n",
    "        open(output_file_lang_1, 'w') as f_out_lang1, \\\n",
    "        open(output_file_lang_2, 'w') as f_out_lang2:\n",
    "        for line_1, line_2 in tqdm(zip(f_lang1, f_lang2), total=num_lines, desc=f\"Deduplicating files\"):\n",
    "            parallel_hash = xxhash.xxh64((line_1.strip() + '\\t' + line_2.strip()).encode('utf-8')).hexdigest()\n",
    "            if parallel_hash not in hashes:\n",
    "                hashes.add(parallel_hash)\n",
    "                f_out_lang1.write(line_1.strip() + '\\n')\n",
    "                f_out_lang2.write(line_2.strip() + '\\n')\n",
    "                num_output_lines += 1\n",
    "\n",
    "    print(f\"Kept {num_output_lines} out of {num_lines} after deduplication\")\n",
    "\n",
    "dedup_file(\n",
    "    'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.en',\n",
    "    'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.ru',\n",
    "    'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en',\n",
    "    'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.ru'\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da4c181a",
   "metadata": {},
   "source": [
    "## Shuffle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "413734bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "!shuf --random-source=data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.en\n",
    "\n",
    "!shuf --random-source=data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.ru > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.ru\n",
    "\n",
    "!paste -d \"\\t\" \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.en \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.ru \\\n",
    "    | head -10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5f3b3640",
   "metadata": {},
   "outputs": [],
   "source": [
    "!rm -rf data/tarred_dataset_en_ru_8k_tokens"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "844a9f26",
   "metadata": {},
   "source": [
    "## Tarred Dataset Creation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2b045df5",
   "metadata": {},
   "outputs": [],
   "source": [
    "!wget https://raw.github.com/NVIDIA/NeMo/main/examples/nlp/machine_translation/create_tarred_parallel_dataset.py \\\n",
    "    -O create_tarred_parallel_dataset.py\n",
    "\n",
    "!python create_tarred_parallel_dataset.py \\\n",
    "    --src_fname data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.en \\\n",
    "    --tgt_fname data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.ru \\\n",
    "    --out_dir data/tarred_dataset_en_ru_8k_tokens \\\n",
    "    --clean \\\n",
    "    --encoder_tokenizer_name yttm \\\n",
    "    --encoder_tokenizer_vocab_size 32000 \\\n",
    "    --encoder_tokenizer_coverage 0.999 \\\n",
    "    --encoder_tokenizer_bpe_dropout 0.1 \\\n",
    "    --decoder_tokenizer_name yttm \\\n",
    "    --decoder_tokenizer_vocab_size 32000 \\\n",
    "    --decoder_tokenizer_coverage 0.999 \\\n",
    "    --decoder_tokenizer_bpe_dropout 0.1 \\\n",
    "    --max_seq_length 512 \\\n",
    "    --min_seq_length 1 \\\n",
    "    --tokens_in_batch 8000 \\\n",
    "    --lines_per_dataset_fragment 100000 \\\n",
    "    --num_batches_per_tarfile 20\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "990265e5",
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls data/tarred_dataset_en_ru_8k_tokens"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc5e123b",
   "metadata": {},
   "outputs": [],
   "source": [
    "!cat data/tarred_dataset_en_ru_8k_tokens/metadata.tokens.8000.json"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
